import 'dart:ui' as ui;

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';

import '../../resources/l10n/kq_intl.dart';

/// @author 高裕
/// 注塑机多段温度
class ImmTemperatureView extends StatefulWidget {
  const ImmTemperatureView({super.key, this.data});

  /// 用逗号隔开的熔体温度
  final String? data;

  @override
  State<StatefulWidget> createState() => ImmTemperatureViewState();
}

class ImmTemperatureViewState extends State<ImmTemperatureView> {
  List<String> value = ['-', '-', '-', '-', '-'];

  @override
  void initState() {
    super.initState();
    if (widget.data != null) {
      value = widget.data!.split(',');
      if (value.length < 5) {
        for (int i = value.length; i < 5; i++) {
          value.add('-');
        }
      } else if (value.length > 5) {
        value = value.sublist(0, 5);
      }
    }
  }

  @override
  void didUpdateWidget(covariant ImmTemperatureView oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.data != null) {
      value = widget.data!.split(',');
      if (value.length < 5) {
        for (int i = (value.length - 1); i < 5; i++) {
          value.add('-');
        }
      } else if (value.length > 5) {
        value = value.sublist(0, 5);
      }
    } else {
      value = ['-', '-', '-', '-', '-'];
    }
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (context, constraints) {
      double width = constraints.maxWidth;
      double height = constraints.maxHeight;
      return SizedBox(
        width: width,
        height: height > 88.r ? 88.r : height,
        child: CustomPaint(
          painter: ImmTemperaturePainter(value: value),
        ),
      );
    });
  }
}

class ImmTemperaturePainter extends CustomPainter {
  ImmTemperaturePainter({required this.value});

  final List<String> value;

  final Paint gradientPaint = Paint()..style = PaintingStyle.fill;
  final Paint whitePaint = Paint()
    ..style = PaintingStyle.fill
    ..color = Colors.white;

  @override
  void paint(Canvas canvas, Size size) {
    double width = size.width;
    double height = size.height;
    double temperaturePartWidth = (width - 56.r) / 5; // 每段温度的宽度(动态),高度写死40.r
    List<double> temperaturePartCenterDxList = [];

    // 喷口
    Path path1 = Path();
    path1.moveTo(0, 32.r);
    path1.lineTo(0, 56.r);
    path1.lineTo(15.r, 63.r);
    path1.lineTo(30.r, 63.r);
    path1.lineTo(30.r, 25.r);
    path1.lineTo(15.r, 25.r);
    path1.close();
    _drawPathPart(canvas, Offset(0, 25.r), Offset(30.r, 63.r), path1);

    // 温度段
    for (int i = 0; i < value.length; i++) {
      double startDx = 30.r + (2.r * (i + 1)) + (temperaturePartWidth * i);
      double endDx = startDx + temperaturePartWidth;
      _drawTemperaturePart(
          canvas, Offset(startDx, 24.r), Offset(endDx, 64.r), value[i]);
      temperaturePartCenterDxList.add(startDx + (temperaturePartWidth / 2));
    }

    // 尾部
    _drawRRectPart(
        canvas, Offset(width - 14.r, 26.r), Offset(width, 62.r), 1.r);

    // 加料口
    double lastTemperaturePartCenterDx =
        temperaturePartCenterDxList[value.length - 1];
    Path path2 = Path();
    path2.moveTo(lastTemperaturePartCenterDx - 18.r, 0);
    path2.lineTo(lastTemperaturePartCenterDx - 11.r, 12.r);
    path2.lineTo(lastTemperaturePartCenterDx - 11.r, 24.r);
    path2.lineTo(lastTemperaturePartCenterDx + 11.r, 24.r);
    path2.lineTo(lastTemperaturePartCenterDx + 11.r, 12.r);
    path2.lineTo(lastTemperaturePartCenterDx + 18.r, 0);
    path2.close();
    _drawPathPart(canvas, Offset(lastTemperaturePartCenterDx - 18.r, 0),
        Offset(lastTemperaturePartCenterDx + 18.r, 24.r), path2);

    // 底部文本
    for (int i = 0; i < value.length; i++) {
      _drawBottomText(
          canvas,
          temperaturePartCenterDxList[i],
          height,
          (i + 1).toString() + KqIntl.currentResource.segment,
          temperaturePartWidth);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }

  /// 绘制路径图块
  _drawPathPart(Canvas canvas, Offset from, Offset to, Path path) {
    _setPaintShader(gradientPaint, from, to);
    canvas.drawPath(path, gradientPaint);
  }

  /// 绘制矩形图块
  _drawRRectPart(Canvas canvas, Offset from, Offset to, double radius) {
    _setPaintShader(gradientPaint, from, to);
    canvas.drawRRect(
        RRect.fromRectAndRadius(
            Rect.fromPoints(from, to), Radius.circular(radius)),
        gradientPaint);
  }

  /// 绘制每段温度块
  _drawTemperaturePart(Canvas canvas, Offset from, Offset to, String text) {
    _setPaintShader(gradientPaint, from, to);
    canvas.drawRRect(
        RRect.fromRectAndRadius(
            Rect.fromPoints(from, to), Radius.circular(1.r)),
        gradientPaint);
    canvas.drawRRect(
        RRect.fromRectAndRadius(
            Rect.fromPoints(Offset(from.dx + 8.r, from.dy + 8.r),
                Offset(to.dx - 8.r, to.dy - 8.r)),
            Radius.circular(1.r)),
        whitePaint);
    TextPainter textPainter = TextPainter(
        text: TextSpan(
            text: text,
            style: TextStyle(
                fontSize: 14.sp,
                color: const Color(0xFF262626),
                fontWeight: FontWeight.w500)),
        textDirection: TextDirection.ltr)
      ..layout(minWidth: 0, maxWidth: to.dx - from.dx - 16.r);
    Offset center = Offset(
        from.dx + ((to.dx - from.dx) / 2), from.dy + ((to.dy - from.dy) / 2));
    Offset textStart = Offset(center.dx - (textPainter.size.width / 2),
        center.dy - (textPainter.size.height / 2));
    textPainter.paint(canvas, textStart);
  }

  /// 绘制底部文本
  _drawBottomText(Canvas canvas, double centerDx, double parentHeight,
      String text, double maxWidth) {
    TextPainter textPainter = TextPainter(
        text: TextSpan(
            text: text,
            style: TextStyle(fontSize: 14.sp, color: const Color(0xFF262626))),
        textDirection: TextDirection.ltr)
      ..layout(minWidth: 0, maxWidth: maxWidth);
    Offset textStart = Offset(centerDx - (textPainter.size.width / 2),
        parentHeight - textPainter.size.height);
    textPainter.paint(canvas, textStart);
  }

  /// 设置画笔shader
  _setPaintShader(Paint paint, Offset from, Offset to) {
    paint.shader = ui.Gradient.linear(
      from,
      Offset(from.dx, to.dy), // dx相同，渐变才会是垂直的
      const <Color>[
        Color(0xFF29323B),
        Color(0xFF5F758C),
        Color(0xFF29323B),
      ],
      const <double>[0, 0.5, 1.0],
    );
  }
}
